<?php
class ImportXmlPageAdminForm extends Form
{
	function ImportXmlPageAdminForm(){
		Form::Form('ImportXmlPageAdminForm');
		CGlobal::$website_title="Import Pages To Xml";
	}
	
	function draw(){
		global $display;
        $xml = simplexml_load_file(ROOT_PATH . 'export/pages.xml');
        if(!$xml){
            echo 'Ko có file pages.xml trong thư mục export';
            return;
        }
        $total_imported = 0;
        $pages = array();
        $modules = array();
        $re = DB::query('SELECT * FROM  `page` ');
        if($re){
            while ($row=mysql_fetch_assoc($re)){
                $pages[$row['name']] = $row;
            }
        }
        $re = DB::query('SELECT * FROM  `module` ');
        if($re){
            while ($row=mysql_fetch_assoc($re)){
                $modules[$row['name']] = $row;
            }
        }
        foreach($xml->children() as $page){
            $new_page = array();
            $new_page['name'] = $page->getName();
            $new_page['description'] = (string)$page->description;
            $new_page['title'] = (string)$page->title;
            $new_page['layout'] = (string)$page->layout;

            if(isset($pages[$new_page['name']])){
                //trường hợp đã tồn tại, update
//                echo 'Page '.$new_page['name'].' đã tồn tại. Bỏ qua!<br/>---------------------------------<br/>';
            }else{
                //trường hợp new page, insert vào db
                $new_page['id'] = $module_data['page_id'] = DB::insert('page', $new_page);
                $pages[$new_page['name']] = $new_page;
                foreach($page->children() as $child){
                    if($child->getName() == 'regions'){
                        foreach($child as $region){
                            $attributes = $region->attributes();
                            $module_data['region'] = (string)$attributes['name'];
                            foreach($region as $module){
                                $module_attributes = $module->attributes();
                                $module_name = (string)$module_attributes['name'];
                                $module_data['position'] = (int)$module_attributes['position'];
                                $module_data['container_id'] = (int)$module_attributes['container'];
                                if(isset($modules[$module_name])){
                                    $module_data['module_id'] = $modules[$module_name]['id'];
                                    $id = DB::insert('block', $module_data);
                                }
                            }
                        }
                    }
                }
                echo 'Imported '.$new_page['name'] . ' thành công!<br/>---------------------------------<br/>';
                $total_imported++;
            }
        }
        echo 'IMPORT DONE!!! '. $total_imported .' page đã được import!';
	}
}
?>